package web.PetStore.web.servlet;

import web.PetStore.domain.Account;
import web.PetStore.domain.Cart;
import web.PetStore.domain.Log;
import web.PetStore.domain.Order;
import web.PetStore.service.CartService;
import web.PetStore.service.LogService;
import web.PetStore.service.OrderService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@WebServlet(name = "CartServlet", urlPatterns = {"/Cart"})
public class CartServlet extends HttpServlet {
    private CartService cartService = new CartService();
    private OrderService orderService = new OrderService();
    private LogService logService = new LogService();
    private List<Cart> newCartList = new ArrayList<>();
    private List<Integer> idList = new ArrayList<>();
    private List<Order> orderList = new ArrayList<>();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        List<Cart> cartList = (List<Cart>) session.getAttribute("cartList");
        Account loginUser = (Account) session.getAttribute("loginUser");

        for(int i = 0;i < cartList.size();i++){
            if(req.getParameter("ck" + i) == null){
                continue;
            }
            Cart cart = cartList.get(i);
            cart.setNum(Integer.parseInt(req.getParameter("num" + i)));
            cart.setPrice(cart.getUnitprice().multiply(BigDecimal.valueOf(cart.getNum())));
            logService.newLog(new Log(loginUser.getUserid(),"下单了-" + cart.getNum() + "-只-" + cart.getName() + "宠物"));
            newCartList.add(cart);
            idList.add(cart.getCartid());
        }
        if(newCartList.isEmpty()){
            req.getRequestDispatcher("/CartForm").forward(req,resp);
            return;
        }

        cartService.deleteCartByCartid(idList);
        session.setAttribute("cartList", newCartList);
        orderList = orderService.cartToOrder(newCartList);
        session.setAttribute("confirmOrderList", orderList);
        req.getRequestDispatcher("/ConfirmOrderForm").forward(req,resp);
    }
}
